import Vue from "vue";
import VueI18n from "vue-i18n";
import ElementLocale from 'element-ui/lib/locale'
import moment from "moment";
import store from "@/store";

Vue.use(VueI18n)


moment.locale('us', {
    week: {
        dow: 1, 
        doy: 4  
    }
});


const defaultLang = store.state.settings.systemLang || 'zh-CN'

const i18n = new VueI18n({
    locale: '',
    fallbackLocale: defaultLang,
    messages: {}
})

const loadedLanguages  = []




const setI18nLanguage = (lang) => {
    i18n.locale = lang
    store.commit('app/SET_LOCALANG', lang)

    console.log('【系统提示】：：多语言切换成功')
    return lang
}

i18n.loadLanguageAsync = async (lang) => {
    if(i18n.locale !== lang) {
        if(!loadedLanguages.includes(lang)) {
            let [local_lang, element_lang] = [
                await import(`@/i18n/lang/${lang}`),
                await import(`element-ui/lib/locale/lang/${ lang }`)
            ]

            // console.log('local_lang', local_lang)
            i18n.setLocaleMessage(lang, {
                ...local_lang.default,
                ...element_lang.default,
            })
            
            loadedLanguages.push(lang)
            return setI18nLanguage(lang)
        }
        return setI18nLanguage(lang)
    }
    return lang
}


ElementLocale.i18n((key, value) => {
    return i18n.t(key, value)
});

// 这里做一个复用缓冲在这里，可以通过设置_i18Name  来复用页面的配置项
Vue.prototype.$ct = function (key, ...args) {
    return i18n.t(`${this.$options._i18Name || this.$options.name }.${key}`, ...args);
}

export default i18n